<?php
  class SellPlugin 
       {
       var $ld;
       var $bot;
       var $rep;
       var $xmlsFName;
       var $xmlsOb;
    
    function SellPlugin()
       {
        $this->ld = new LocalData();
        $bot = new Bot();
        $this->xmlsOb = new xmlsOb();
		    $xmlsFNameObj = new xmlsLang();
		    $this->xmlsFName = $xmlsFNameObj->langXML;
       }
    
    function flN($item) 
       {
		    if (!isset($this->xmlsFName) || empty($this->xmlsFName)) {return '-';}
		    if (isset($this->xmlsFName[$item]) && (!empty($this->xmlsFName[$item]))) 
         {return ((string)$this->xmlsFName[$item]);} 
        else {return '';}
	     }
    
    function NlistCheck() 
       {
        $is = false;
        $res = ($this->ld->GetSelect('SELECT count(*) as cnt FROM sqlite_master where tbl_name="Sell"'));
        if ($res[0]["cnt"]==1) {$is = true;}
        return $is;
       }
   
    function GetNList() 
       {
        $res = "";
        $sel = ($this->ld->GetSelect('SELECT count(*) as cnt FROM sqlite_master where tbl_name="Sell"'));
        if ($sel[0]["cnt"] == 1) {$sel = ($this->ld->GetSelect('SELECT count(*) as cnt FROM Sell'));
            if ($sel[0]["cnt"] > 0) {$sel = ($this->ld->GetSelect('SELECT value FROM Sell'));
                foreach ($sel as $n){
                    $tmp=array();
                    $tmp=unserialize(base64_decode($n['value']));
                    $res[]= array( 'uid'=>$tmp['uid'], 'cityname'=>$tmp['cityname'] ) ; 
                   }}}
        return $res;
       }
       
    function ImageUrl($name) 
       {
		    $dir = substr($_SERVER["PHP_SELF"], 0, strpos($_SERVER["PHP_SELF"], "/"));		
		    $name = trim($name);
		    $sel = "SELECT url FROM Images WHERE ItemName ='".$name."'";
		    $res = $this->ld->GetSelect($sel) ;
		    if ($dir.$res[0]['url'] == $dir ) {return "";}
         else {return str_replace("/","\\", $dir.$res[0]['url']);}
	     }
       
    function LocalImageUrl($name) 
       {
		    $dir = substr($_SERVER["PHP_SELF"], 0, strpos($_SERVER["PHP_SELF"], "/")).'Plugins/Sell/';		
		    $name = trim($name);
		    return str_replace("/","\\", $dir.$name);
	     }
        
    function GetParamByName($name) 
       {
		    $fl = file('options.txt');
		    foreach ($fl as $line) {if (strpos($line, $name) !== false) 
         {$pos = strpos($line, '=');$val = trim(substr($line, $pos + 1, strlen($line)));}}
		    return $val;
	     }
            
    function GetMobjects()
       {   
       function mmp ($a, $b) {return $a['id'] > $b['id'];} 
        
        $rep=Array();
        $res=$this->ld->GetSelect("SELECT * FROM objects");
        if (!$res) { return "<option>DB ERROR</option>"; }
        $is=1;
        
        usort($res, "mmp");krsort($res); 
        
       foreach ($res as $val){ 
            $v=(string)$val[1];
            $obj=unserialize(base64_decode($v));                    
            $rep["obj"][$i] = $obj;
            $i++; }
    
       foreach ($rep["obj"] as $value)
          {$fname = '&nbsp; --> '.$this->flN((string)$value['itemName']);
        
        $Mlist .= '<option value="'.$value['id'].'">&nbsp;Id&laquo;'.$value['id'].'&nbsp;&nbsp;-&nbsp;&nbsp;
                                  '.$value['className'].'&nbsp;&nbsp;-&nbsp;&nbsp;'.$value['itemName'].$fname.'</option>';
          }
              return $Mlist;
       }
    
    function GetDTobjects()
       {   
       function dmp ($a, $b) {return $a['id'] > $b['id'];}  
        
        $rep=Array();
        $res=$this->ld->GetSelect("SELECT * FROM dt_objects");
        if (!$res) { return "<option>DB ERROR</option>"; }
        $is=1;
        
        usort($res, "dmp");krsort($res); 
        
       foreach ($res as $val){ 
            $v=(string)$val[1];
            $obj=unserialize(base64_decode($v));                    
            $rep["obj"][$i] = $obj;
            $i++; }
    
       foreach ($rep["obj"] as $value)
          {$fname = '&nbsp; --> '.$this->flN((string)$value['itemName']);
        
        $Dlist .= '<option value="'.$value['id'].'">&nbsp;Id&laquo;'.$value['id'].'&nbsp;&nbsp;-&nbsp;&nbsp;
                                  '.$value['className'].'&nbsp;&nbsp;-&nbsp;&nbsp;'.$value['itemName'].$fname.'</option>';
          }
              return $Dlist;
       }
    
    function GetMainobjects()
       {   
       function mop ($a, $b) {return $a['id'] > $b['id'];} 
        
        $rep=Array();
        $res=$this->ld->GetSelect("SELECT * FROM objects");
        if (!$res) { return "<option>DB ERROR</option>"; }
        $is=1;
        
        usort($res, "mop");krsort($res); 
        
       foreach ($res as $val){ 
            $v=(string)$val[1];
            $obj=unserialize(base64_decode($v));                    
            $rep["obj"][$i] = $obj;
            $i++; }
    
       foreach ($rep["obj"] as $value)
          {
                
        $Mobjlist .= '<tr><td align="center">'.$value['id'].'&nbsp;</td><td>&nbsp;'.$value['itemName'].'&nbsp;</td>
                          <td >&nbsp;'.$value['className'].'&nbsp;</td><td >&nbsp;'.$value['state'].'&nbsp;</td>
                          <td >&nbsp;'.$value['position']['x'].'&nbsp;</td><td >&nbsp;'.$value['position']['y'].'&nbsp;</td>
                          <td >&nbsp;'.$value['itemOwner'].'&nbsp;</td></tr>';
          }
              return $Mobjlist;
       }
       
    function GetDownobjects()
       {   
       function dop ($a, $b) {return $a['id'] > $b['id'];} 
        
        $rep=Array();
        $res=$this->ld->GetSelect("SELECT * FROM dt_objects");
        if (!$res) { return "<option>DB ERROR</option>"; }
        $is=1;
        
        usort($res, "dop");krsort($res); 
        
       foreach ($res as $val){ 
            $v=(string)$val[1];
            $obj=unserialize(base64_decode($v));                    
            $rep["obj"][$i] = $obj;
            $i++; }
    
       foreach ($rep["obj"] as $value)
          {
                
       $DTobjlist .= '<tr><td align="center">'.$value['id'].'&nbsp;</td><td>&nbsp;'.$value['itemName'].'&nbsp;</td>
                          <td >&nbsp;'.$value['className'].'&nbsp;</td><td >&nbsp;'.$value['state'].'&nbsp;</td>
                          <td >&nbsp;'.$value['position']['x'].'&nbsp;</td><td >&nbsp;'.$value['position']['y'].'&nbsp;</td>
                          <td >&nbsp;'.$value['itemOwner'].'&nbsp;</td></tr>';
          }
              return $DTobjlist;
       }
    
    function GetInfoFromDB()
       {
        $this->rep=Array();
        $res=$this->ld->GetSelect("select * from objects");
        foreach ($res as $val){$v=(string)$val[1];
            $obj=unserialize(base64_decode($v));
            $this->rep["classes"][$obj['className']][$obj['itemName']][]=1;}
       }
    
    function ObjectTable($rep)
       {
        $res='<table width="600" border="1" bordercolor="black" ><tr><td colspan="2" align="center" class="zag">Objects</td></tr>';
        foreach ($rep["classes"] as $key=>$value){
            $res=$res . '<tr><th colspan="2" align="left">'.$key.'</th></tr>';
            foreach ($value as $name=>$count){$res=$res . '<tr><td align="center">'.$name.'</td><td align="center" width="100">'.count($count).'</td></tr>';}}
        $res=$res.'</table>';
        return $res;
       }
    function ObjectMainTable()
	     {
		    $res=$this->ld->GetSelect("select * from objects ORDER BY className");
        if (!$res) {return "DB ERROR";}
        
		    foreach ($res as $val){
			  $v=(string)$val[1];
			  $obj=unserialize(base64_decode($v));
			  $this->repm["classes"][$obj['className']][$obj['itemName']][]=1;}
    
        $res='<div style="margin-left: 20px"><table width="480" border="3" cellspacing="0" cellpading="0" bordercolor="black" >
              <tr style="background-color: #566D7E;"><td colspan="2" align="center" class="zag">
              <font color="#FFFFFF">OBJECTS MAIN</font></td></tr>';
          
        foreach ($this->repm["classes"] as $key=>$value) { 
		             $res=$res . '<tr style="background-color: #95B9C7;"><th colspan="2" align="left">'.$key.'</th></tr>';
		    foreach ($value as $name=>$count){ 
        if ($this->ImageUrl($name) == ""){$res=$res . '<tr style="background-color: #FFFFFF;"><td align="center" width="250">'.$name.'</td>
                                                       <td align="center" width="50"><font color="#0000FF">'.count($count).'</FONT></td></tr>';} 
                                                       
        else {$res=$res . '<tr style="background-color: #FFFFFF;"><td align="center" width="250"><img src="'.$this->ImageUrl($name).'" alt="'.$name.'"></td>
                           <td align="center" width="50"><font color="#0000FF">'.count($count).'</FONT></td></tr>';}}}
		    $res=$res.'</table>';
		    return $res;
	     }
       
    function ObjectDownTable()
	     {
		    $res=$this->ld->GetSelect("select * from dt_objects ORDER BY className");
        if (!$res) {return "DB ERROR";}
        
        foreach ($res as $val){
			  $v=(string)$val[1];
			  $obj=unserialize(base64_decode($v));
			  $this->repdt["classes"][$obj['className']][$obj['itemName']][]=1;}
             
        $res='<div style="margin-left: 20px"><table width="480" border="3" cellspacing="0" cellpading="0" bordercolor="black" >
              <tr style="background-color: #566D7E;"><td colspan="2" align="center" class="zag">
              <font color="#FFFFFF">OBJECTS DOWNTOWN</font></td></tr>';
          
		    foreach ($this->repdt["classes"] as $key=>$value){
		             $res=$res . '<tr style="background-color: #95B9C7;"><th colspan="2" align="left">'.$key.'</th></tr>';
		    foreach ($value as $name=>$count){
		    if ($this->ImageUrl($name) == ""){$res=$res . '<tr style="background-color: #FFFFFF;"><td align="center" width="250">'.$name.'</td>
                                                       <td align="center" width="50"><font color="#0000FF">'.count($count).'</FONT></td></tr>';} 
                                                       
        else {$res=$res . '<tr style="background-color: #FFFFFF;"><td align="center" width="250"><img src="'.$this->ImageUrl($name).'" alt="'.$name.'"></td>
                           <td align="center" width="50"><font color="#0000FF">'.count($count).'</FONT></td></tr>';}}}
		    $res=$res.'</table>';
		    return $res;
	     }
         
    function GetForm($server)
       {
       
       $settings = (array) $this->ld->GetPlSettings('Sellplugin');
    
   echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
               <html xmlns="http://www.w3.org/1999/xhtml" lang="ru">
       <head>
          <title>Sell helper</title>
          <script src="..\..\codebase-php\jquery-1.4.2.min.js"></script>
          <script src="..\..\codebase-php\jquery.json-2.2.min.js"></script>
          <link href="helpers/menu.css" rel="stylesheet" type="text/css">
          <link href="helpers/plugin.css" rel="stylesheet" type="text/css">
       <script type="text/javascript" src="helpers/menu.js"></script>
        <!--[if lte IE 7]>
       <style>
         menuwrapper, #p7menubar ul a {height: 1%;}
         a:active {width: auto;}
       </style>
       <![endif]-->
        <script>
        //======================================================================
            $(document).ready(function(){
                            window.settings=eval(' . json_encode($this->ld->GetPlSettings('Sellplugin')) . ');

                            //==============================================================
							             if ((window.settings!==null) && (window.settings!==undefined)){
								              $("#itemid").val(window.settings.itemid);
								              $("#dt_itemid").val(window.settings.dt_itemid);
                              
								              $(":checkbox").each(function(){
									                       if(window.settings[$(this).attr("id")]==true){
										                          $(this).attr("checked", true);
									                       }else{
										                          $(this).attr("checked", false);
									                       }});
							             }
                            //==============================================================
							             $("#btn_save").click(function(){
								           var req=new Object();
                           
								           req.itemList=new Array();
								           $("#itemid option:selected").each(function(){
									         req.itemList.push($(this).val());
								              });
								
								           req.dt_itemList=new Array();
								           $("#dt_itemid option:selected").each(function(){
									         req.dt_itemList.push($(this).val());
								              });
								
								           $(":checkbox").each(function(){
									         var par=$(this).attr("id");
                           req[par]=$(this).attr("checked");
								              });

								                data=$.toJSON(req);
								                var l=window.location.toString();
								                var indx=l.indexOf(\'?\');
								                var nurl=l.slice(0, indx)+"?action=save&tmp="+Math.random();
                                $.post(nurl, data, function(r) {$("#debug").html( r ); alert("Are you sure you want to SELL? \n\n [..Press OK..]"); });
                                
								                
								                                              //alert(req.itemList);	
								                return false;
							                 });
						               });
        //======================================================================
       </script>
       </head>
       <body>
        <form >
                <div class="zag" height="35">&nbsp;&nbsp;Sell &nbsp;&nbsp;<span style="font-size:smaller;font-weight:bold;">Version 1.2 &nbsp;&nbsp;May &nbsp;2012</span><hr></div>

       <table id="maint" border="2" size="700">
       <tr id="up">
       <tr BGCOLOR="#EFEFEF"><td>&nbspYour choice to Sell / or in Inventory&nbsp;</td><td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b> Main / Downtown </b></td></tr>';
    
                  $Mlist = $this->GetMobjects();
							    $Dlist = $this->GetDTobjects();
                  
                  $Mobjlist = $this->GetMainobjects();
                  $DTobjlist = $this->GetDownobjects();
   
   echo '</table><br><span style="font-size:smaller;">
                  <tr><td>&nbsp;Item send to (default <b>Sell</b> / Inventory)&nbsp;
                  <input id="SellTo" type="checkbox"></td></tr></span><br><br>
                  <input id="Sell" type="checkbox" value="0" size="4"> &nbsp;<b>Start sell as to next cycle</b> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                  
                  <button id="btn_save" style="color:white;background-color:#13a89e;border-width:2px;border-style:solid; ">Save &nbsp;Settings</button>
                  &nbsp;&nbsp;
                  <input style="color:white;background-color:#13a89e;border-width:2px;border-style:solid;"type="button" value="Reload" onclick="window.location.reload()" />
                  </form>';
    
   echo '<div id="menuwrapper">
          <ul id="p7menubar">
              <li><a href="/Plugins/Sell/Main.php?action=menu&click=home"><b>Get Info</b></a></li>
              <li><a href="/Plugins/Sell/Main.php?action=menu&click=main"><b> Main </b></a></li>
              <li><a href="/Plugins/Sell/Main.php?action=menu&click=down"><b> Downtown </b></a></li>
               <li><a class="trigger" href="#"><b> Show Objects </b></a>
                <ul>
                <li><a href="/Plugins/Sell/Main.php?action=menu&click=mainobj"> Main </a></li>
                <li><a href="/Plugins/Sell/Main.php?action=menu&click=dtobj"> Downtown </a></li>
                </ul>
              <li><a class="trigger" href="#"><b>Look Object States</b></a>
                <ul>
                <li><a href="/Plugins/Sell/Main.php?action=menu&click=infomain">State Main</a></li>
                <li><a href="/Plugins/Sell/Main.php?action=menu&click=info_dt">State Downtown</a></li>
          </ul>    

       <br class="clearit">
        <script language="javascript">
        P7_ExpMenu()
        </script>
        
        </div><table id="maint" border="0"><br>'; 
       
       $imagePath = substr($_SERVER["PHP_SELF"], 0, strpos($_SERVER["PHP_SELF"], "/"));
    
    if($server['click'] == "home")
       {
       echo '<span style="font-size:smaller;">';
       echo '<b>Sell Plugin for City Ville</b><br>';
       echo 'Original Code by 12Christiaan, Special Thanks to Little Todd & Xfiles<br><br>';
       echo '<b>Recoding & new Design by Demian Kinley';
       echo '<br>';
       echo 'written 01-05-2012</b><br>';
       echo '<br>';
       echo 'This Plugin allows you to remove Items (Objects) from your Cities<br> 
             Be careful, if your City is now loading any more, because there are faulty Items in your Cities ( Main or Downtown )<br>
             <br>
             !! Use this with extrem warning, this can break your City (even more) !!<br>
             <br>
             <b>How to start</b><br>
             <br>
             &nbsp;-&nbsp;To switch, select City ! If you want refresh, hit Reload button !<br>
             &nbsp;-&nbsp;Look into list, select Id that you need to remove from your City <br>
             <br>
             &nbsp;-&nbsp;Goodie, Sell <b>[NOT recoverable]</b> / (or sent into your Inventory)<br> 
             &nbsp;-&nbsp;click checkbox and hit Save Settings<br> 
             <br> 
             &nbsp;-&nbsp;Click the checkbox below to run the Plugin for the next cycle
             <br>
             &nbsp;-&nbsp;Use shift / ctrl for multi select and hit Save Settings <br><br></div></span>';
       }
    
    if($server['click'] == "main")
       {
       echo '<tr><td><b>&nbsp;&nbsp;&nbsp; Id  &nbsp;&nbsp;- / -  Classname  &nbsp;&nbsp;- / - Item_Name  &nbsp;&nbsp;- / -  Real Name &nbsp;&nbsp;&nbsp;</b>
                     Actualy World &laquo;<b>&nbsp;Main</b></td></tr>';
       echo '<tr><td colspan="2"><table style="border:2px solid black;width:620px"><select style=width:620px; multiple="multiple" size="35" id="itemid" name="itemid">';
       echo '<b><option>Do not Sell all Items</option>';
       
       echo $Mlist;
       echo '</select></td></tr></table>';
       echo 'Use shift / ctrl for multi select and hit Save Settings&nbsp;';
       }
                                                              
    if($server['click'] == "down")
       {
       echo '<tr><td><b>&nbsp;&nbsp;&nbsp; Id  &nbsp;&nbsp;- / -  Classname  &nbsp;&nbsp;- / - Item_Name  &nbsp;&nbsp;- / -  Real Name &nbsp;&nbsp;&nbsp;</b>
                     Actualy World &laquo;<b>&nbsp;Downtown</b></td></tr>';
       echo '<tr><td colspan="2"><table style="border:2px solid black;width:630px"><select style=width:630px; multiple="multiple" size="35" id="dt_itemid" name="dt_itemid">';
       echo '<b><option>Do not Sell all Items</option>';
       
       echo $Dlist;
       echo '</select></td></tr></table>';
       echo 'Use shift / ctrl for multi select and hit Save Settings&nbsp;';
       }
    
    if($server['click'] == "infomain") 
       {
       echo '<tr><td>&nbsp;Actualy World &laquo;<b>&nbsp;Main</b></td></tr>'; 
       echo '<table border="2" "background-color:#99CCFF;" > 
             <tr><td><b>&nbsp;Id&nbsp;</b></td>
             <td><b>&nbsp;Item_Name / Objects&nbsp;</b></td>
             <td><b>&nbsp;Classname / Types&nbsp;</b></td>
             <td><b>&nbsp;State&nbsp;</b></td>
             <td><b>&nbsp;Pos_X&nbsp;</b></td>
             <td><b>&nbsp;Pos_Y&nbsp;</b></td>
             <td><b>&nbsp;Item Owner&nbsp;</b></td>
             <td></td>
             </tr>'; 
       
       echo $Mobjlist;
       
       echo '</table>';
       }  
       
    if($server['click'] == "info_dt") 
       {
       echo '<tr><td>&nbsp;Actualy World &laquo;<b>&nbsp;Downtown</b></td></tr>'; 
       echo '<table border="2" "background-color:#99CCFF;" > 
             <tr><td><b>&nbsp;Id&nbsp;</b></td>
             <td><b>&nbsp;Item_Name / Objects&nbsp;</b></td>
             <td><b>&nbsp;Classname / Types&nbsp;</b></td>
             <td><b>&nbsp;State&nbsp;</b></td>
             <td><b>&nbsp;Pos_X&nbsp;</b></td>
             <td><b>&nbsp;Pos_Y&nbsp;</b></td>
             <td><b>&nbsp;Item Owner&nbsp;</b></td>
             <td></td>
             </tr>'; 
       
       echo $DTobjlist;
       
       echo '</table>';
       } 
       
    if($server['click'] == "mainobj")
       {
       echo '<body><td><div class="collapsibleContainer" title="Collapsible Panel">';
       echo  $this->ObjectMainTable();  
       echo '</td></div></div></body>';
       }
              
    if($server['click'] == "dtobj")
       {
       echo '<body><td><div class="collapsibleContainer" title="Collapsible Panel">';
       echo  $this->ObjectDownTable();  
       echo '</td></div></div></body>';
       } 
         
       echo '....Select Cities</body></html>';  
       
       }
       }
    
       class xmlsLang {
	       var $langXML;
         
	  function xmlsLang() 
       {
		    $langdir = substr($_SERVER["PHP_SELF"],0,strpos($_SERVER["PHP_SELF"],"/")).'tmp_dir\en_US.xml';
		    $langs = simplexml_load_file($langdir);
		    $arFname = array();
        
       foreach ($langs->pkg as $pkg) {if ($pkg['name'] == 'Items') {
			 foreach ($pkg->string as $fname) {$fkey = substr((string)$fname['key'], 0, strpos((string)$fname['key'], '_friendlyName'));
          if (!empty($fkey)) {$arFname[$fkey] = (string)$fname->original;}}}}
		    $this->langXML = $arFname;
	     }
       
       }
?>


              
              